package com.zzn.bookManage.controller;

import com.zzn.bookManage.pojo.User;
import com.zzn.bookManage.service.UserService;
import com.zzn.bookManage.util.ObjectHolder;
import com.zzn.bookManage.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 修改用户密码
 */

@WebServlet("/changePassword")
public class ChangePassword extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(true); // 必定获得一个session

        String oldPassword = req.getParameter("oldpassword");
        String newPassword = req.getParameter("newpassword");
        User loginUser = (User) session.getAttribute("loginUser");

        if (StringUtil.isBlank(oldPassword)||StringUtil.isBlank(newPassword)){
            req.setAttribute("msg","密码不能为空");
            req.getRequestDispatcher("/setting.jsp").forward(req, resp);
            return;
        }

        loginUser.setPassword(newPassword);
        UserService userService = ObjectHolder.getInstance().getUserService();
        if (userService.changeUserPassword(loginUser)){
            // 修改成功
            req.setAttribute("msg","修改密码成功");
            session.setAttribute("loginUser",loginUser);
            req.getRequestDispatcher("/setting.jsp").forward(req, resp);
        }else{
            // 修改失败
            req.setAttribute("msg","修改密码失败");
            req.getRequestDispatcher("/setting.jsp").forward(req, resp);
        }
    }
}
